#include "stdafx.h"
#include "window.h"
#include "ui_window.h"
#include <model/scene.h>
#include <model/potion.h>
#include <model/mage.h>
#include <model/spell.h>
#include <control/keyboardplayercontrol.h>

Window::Window(QWidget *parent) :
    QGLWidget(parent),
    ui(new Ui::Window),
    _width(800),
    _height(600)
{
    ui->setupUi(this);
    setFixedSize(_width, _height);
}

Window::~Window()
{
    delete ui;
}

void Window::initializeGL()
{
    glClearColor(0.0, 0.0, 0.0, 1);
    glEnable(GL_BLEND);
    glEnable(GL_ALPHA_TEST);
    //glEnable(GL_DEPTH_TEST);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    //glEnable(GL_MULTISAMPLE);

    _gameHandler.setSize(_width, _height);
    _gameHandler.setInterval(25);
    _gameHandler.addPlayer(Player(&_keyboardControl, "myself"));
    _gameHandler.addPlayer(Player(&_nullControl, "null #1"));
    _gameHandler.addPlayer(Player(&_nullControl, "null #2"));

    _renderer.init();
    _gameHandler.startGame();
    connect(&_gameHandler, SIGNAL(turnEnd()), this, SLOT(updateGL()));
}

void Window::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    const Scene *scene = _gameHandler.scene();
    if (scene)
        scene->accept(&_renderer);
    else
        qDebug() << "no scene available";
}

void Window::resizeGL(int width, int height)
{
    _width = width;
    _height = height;
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, _width, _height, 0, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
}

void Window::keyPressEvent(QKeyEvent *event)
{
    _keyboardControl.accept(event, true);
}

void Window::keyReleaseEvent(QKeyEvent *event)
{
    _keyboardControl.accept(event, false);
}
